<template>
  <div class="natural_readWord">
    <Header :isTransBg="true" :width="1000" :isGoBack="false">
      <template v-slot:left>
        <span class="weight-title">
          {{(checkedBookData.book_id==2070?'自然拼读':'自然拼读快速版')+'-见词能读'}}
        </span>
      </template>
      <template v-slot:right>
        <div class="close-memeory" @click="goStudyCenter">
          关闭
          <img class="ml5" src="@/assets/img/close-circle.png" alt="" />
        </div>
      </template>
    </Header>

    <div class="natural_readWord_center">
      <div class="natural_readWord_content">
        <div class="title">
          <!-- {{ isIintensiveWord ? "智能听读" : "词义记忆" }} -->
          见词能读
          <span class="feedback" @click="showFeedBack">反馈</span>
        </div>
        <div class="content">
          <div>
            <!-- 单词测试组件 -->
            <StudyWord
              v-if="!isIintensiveWord && wordData.word_id"
              :wordData="wordData"
              @nextWord="nextWord"
              @checkFalseFun="checkFalseFun"
              @closeTimer="closeTimer"
              ref="studyWord"
            ></StudyWord>
            <readWordItem
              ref="readWordItem"
              v-if="isIintensiveWord && intensiveWord.word_id && isShowCom"
              @alreadyRead="alreadyRead"
              :wordData="intensiveWord.question"
            ></readWordItem>
            <TestQuestion
              v-if="false"
              :question="intensiveWord.question"
              @changeStudentAnswer="changeStudentAnswer"
              :isQuick="true"
              ref="testQuestion"
              :isMemory="true"
            >
            </TestQuestion>
          </div>
        </div>
        <div
          style="text-align: right;padding-top: 60px;padding-right: 40px;color: #ffff;"
          v-if="!isIintensiveWord && wordData.word_id"
        >
          <span>
            本次学习：生词：{{ newWordNum }} 熟词：{{ skilledNum }} 本次复习：{{
              reviewNum
            }}
          </span>
        </div>
        <div
          style="text-align: right;padding-top: 60px;padding-right: 40px;color: #ffff;"
          v-if="isIintensiveWord && intensiveWord.word_id"
        >
          <span></span>
          <span>
            进度：{{ intensiveWordIndex + 1 }} / {{ intensiveWordList.length }}
          </span>
        </div>
      </div>
    </div>
    <Feedback
      ref="feedback"
      :type="1"
      :classify="1"
      @openDialog="isOpenMessageBox = true"
      @closeDialog="isOpenMessageBox = false"
    ></Feedback>
  </div>
</template>
<script>
import Header from "@/components/Header";
import StudyWord from "../components/StudyWord";
import TestQuestion from "../components/TestQuestion";
import readWordItem from "../components/readWordItem";
import { getWordQuestions } from "@/api/index";
import { create } from "@/api/naturalSpell";
import Feedback from "@/components/Feedback";
import { throttle } from "@/utils/utils";
import EventBus from "@/assets/js/eventBus";
import {
  getStudyWordList,
  setEstimateWord,
  setWordExercise,
  getMemoryReview,
  setWordPass,
  addIntegral,
  getReviewNumber,
  setIsForce,
} from "@/api/index";
const wordCategory = {
  0: { title: "听读", route: "readWordFast" },
  1: { title: "词听", route: "wordListen" },
  2: { title: "听写", route: "dictationFast" },
  3: { title: "默写", route: "writeMemory" },
};
export default {
  data() {
    return {
      wordList: [],
      wordData: {},
      checkedWordIndex: -1,
      intensiveWordList: [],
      intensiveWordIndex: -1,
      isIintensiveWord: false,
      intensiveWord: {},
      groupData: {},
      initSkilledNum: 0,
      initReviewNum: 0,
      initNewWordNum: 0,
      countTimer: null,
      countTimerNum: 5,
      unitId: null,
      category: 0,
      checkedBookData: null,
      addIntegralNum: 0,
      memoryHelpDialog: false,
      isOpenMessageBox: false,
      isShowCom: true,
      isForce: 0,
      review_number: 0,
    };
  },
  computed: {
    skilledNum() {
      let data = this.wordList.filter((item) => {
        return !item.isReview && item.checkAnswer === true;
      });
      return data.length + this.initSkilledNum;
    },
    reviewNum() {
      let data = this.wordList.filter((item) => {
        return (
          item.isReview &&
          (item.checkAnswer === true || item.checkAnswer === false)
        );
      });
      return data.length + this.initReviewNum;
    },
    newWordNum() {
      let data = this.wordList.filter((item) => {
        return !item.isReview && item.checkAnswer === false;
      });
      return data.length + this.initNewWordNum;
    },
  },
  components: {
    readWordItem,
    StudyWord,
    // StudyQuestion,
    Header,
    Feedback,
    TestQuestion,
  },
  methods: {
    alreadyRead(score, blob,detail) {
      console.log(1122221);
      let is_true = 0;
      if (score >= 60) {
        is_true = 1;
      }
      let question = Object.assign(this.intensiveWord.question, {
        detail,
        score,
        is_true,
        fileData: window.URL.createObjectURL(blob),
        isChecked: true,
      });
      this.changeQuestionItem(question);
      this.checkTrueFun(is_true);
    },
    changeQuestionItem(question) {
      this.isShowCom = false;
      this.$set(this.intensiveWord, "question", question);
      this.$nextTick(() => {
        this.isShowCom = true;
        console.log(this.intensiveWord.question, "151515");
      });
    },
    setIsForce() {
      setIsForce(this.checkedBookData.book_id).then((res) => {
        console.log(res);
      });
    },
    cancelForce() {
      this.isForce = 0;
      this.setIsForce();
    },
    setInitWordNum() {
      let data1 = this.wordList.filter((item) => {
        return !item.isReview && item.checkAnswer === true;
      });
      let data2 = this.wordList.filter((item) => {
        return (
          item.isReview &&
          (item.checkAnswer === true || item.checkAnswer === false)
        );
      });
      let data3 = this.wordList.filter((item) => {
        return !item.isReview && item.checkAnswer === false;
      });
      this.initSkilledNum += data1.length;
      this.initReviewNum += data2.length;
      this.initNewWordNum += data3.length;
    },
    nextIntQuestion(isSkipTag) {
      if (isSkipTag) {
        if(this.isReview){
          this.setWordPass(true)
        }else{
          this.checkTrueFun(true)
        }
        this.nextIntensiveWord();
        return;
      }
      if (this.intensiveWord.question.is_true == 1) {
        this.nextIntensiveWord();
      } else {
        this.changeQuestion();
      }
    },
    changeStudentAnswer(studentAnswer) {
      let is_true = 0;
      if (studentAnswer == this.intensiveWord.question.trueAnswer) {
        is_true = 1;
      }
      let question = Object.assign(this.intensiveWord.question, {
        is_true,
        studentAnswer,
        isChecked: true,
      });
      this.changeQuestion(question);
      this.checkTrueFun(is_true);
    },
    changeQuestion(question) {
      let isInitQuestion = !question;
      if (!question) {
        question = Object.assign(this.intensiveWord.question, {
          isSkipTag: true,
          is_true: null,
          fileData: "",
          score: null,
          studentAnswer: "",
          isChecked: false,
        });
      }
      this.isShowCom = false;
      this.$set(this.intensiveWord, "question", question);
      this.$nextTick(() => {
        this.isShowCom = true;
        this.$nextTick(() => {
          if (isInitQuestion && this.$refs.testQuestion) {
            this.$refs.testQuestion.playAudio("audioPlay");
          }
        });
      });
    },
    showFeedBack() {
      let id = this.isIintensiveWord
        ? this.intensiveWord.word_id
        : this.wordData.word_id;
      if (id) {
        this.$refs.feedback.visible(id);
      }
    },
    //  需要复习的单词两个之后插一个，标记isReview:true
    nextWord: function() {
      console.log(this.wordData);
      if (this.wordList.length <= 0) {
        return;
      }
      //
      if (
        this.checkedWordIndex < this.wordList.length - 1 &&
        this.wordList.length > 0
      ) {
        this.checkedWordIndex++;
        this.setWordData(this.wordList[this.checkedWordIndex]);
      } else {
        this.getStudyData();
      }
    },
    nextIntensiveWord: throttle(function() {
      if (this.intensiveWordList.length <= 0) {
        return;
      }
      if (
        this.intensiveWordIndex < this.intensiveWordList.length - 1 &&
        this.intensiveWordList.length > 0
      ) {
        this.intensiveWordIndex++;
        this.setIntensiveWordData(
          this.intensiveWordList[this.intensiveWordIndex]
        );
      } else {
        this.getStudyData();
      }
    }, 300),
    setIntensiveWordData(data) {
      this.intensiveWord = data;
      this.intensiveWord.startTime = new Date().getTime();
      this.$nextTick(() => {
        if (this.$refs.testQuestion) {
          this.$refs.testQuestion.playAudio("audioPlay");
        }
      });
    },
    setWordData(data) {
      this.wordData = data;
      this.wordData.startTime = new Date().getTime();
      // this.setCountTimer();
      this.$nextTick(() => {
        if (this.$refs.studyWord) {
          this.$refs.studyWord.playAudio("audioPlay");
        }
      });
    },
    recordedData(data, blob) {
      console.log(111111);
      this.$set(this.intensiveWord.question, "score", data.context.score);
      this.$set(
        this.intensiveWord.question,
        "result",
        data.context.lines[0].words[0]
      );
      this.$set(this.intensiveWord.question, "isAnswer", true);
      this.$set(
        this.intensiveWord.question,
        "fileData",
        window.URL.createObjectURL(blob)
      );
      console.log(this.intensiveWord.question, "this.wordData");
    },
    setEstimateWord(not) {
      return new Promise((reslove, reject) => {
        let data = {
          not: not,
          bookId: this.checkedBookData.book_id,
          number: this.checkedBookData.number,
          unitId: this.unitId,
          wordId: this.wordData.word_id,
          groupId: this.groupData.group_id,
          category: this.category,
          useTime: parseInt(
            (this.wordData.endTime - this.wordData.startTime) / 1000
          ),
          wid: this.wordData.wid,
          isStrange: this.wordData.isReview ? 1 : 0,
        };
        setEstimateWord(data)
          .then((res) => {
            reslove(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    setWordPass(not) {
      return new Promise((reslove, reject) => {
        if (not) {
          let num = this.intensiveWord.wrongNum;
          console.log(num);
          let data = {
            category: this.category,
            book_id: this.checkedBookData.book_id,
            word_id: this.intensiveWord.word_id,
            memory_strength: 30 - num * 10 < 0 ? 0 : 30 - num * 10,
          };
          setWordPass(data)
            .then((res) => {
              if (res.code == 200) {
                this.review_number++;
                if (this.isForce && this.review_number >= 40) {
                  this.cancelForce();
                }
              }
              reslove(res);
            })
            .catch((error) => {
              reject(error);
            });
        }
      });
    },

    setWordExercise(not) {
      let useTime = 0;
      if (this.intensiveWord.endTime && this.intensiveWord.startTime) {
        useTime = parseInt(
          (this.intensiveWord.endTime - this.intensiveWord.startTime) / 1000
        );
      }
      if (this.intensiveWord.initUseTime) {
        useTime += this.intensiveWord.initUseTime;
      }
      return new Promise((reslove, reject) => {
        let data = {
          groupId: this.groupData.group_id,
          wid: this.intensiveWord.wid,
          wordId: this.intensiveWord.word_id,
          number: this.checkedBookData.number,
          not: not,
          bookId: this.checkedBookData.book_id,
          unitId: this.unitId,
          useTime: useTime,
          source: this.category,
        };
        setWordExercise(data)
          .then((res) => {
            reslove(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    async checkFalseFun(data, fun) {
      //词义记忆选择认不认识
      this.wordData.endTime = new Date().getTime();
      this.closeTimer();
      if (this.isReview) {
        await this.setWordPass(data);
      } else {
        await this.setEstimateWord(data);
      }
      // this.wordData.checkAnswer = data;
      this.$set(this.wordData, "checkAnswer", data);
      if (!data) {
        if (this.checkedWordIndex + 3 < this.wordList.length) {
          this.wordList.splice(
            this.checkedWordIndex + 3,
            0,
            Object.assign({}, this.wordData, {
              isReview: true,
              checkAnswer: null,
            })
          );
          //
        } else {
          this.wordList.push(
            Object.assign({}, this.wordData, {
              isReview: true,
              checkAnswer: null,
            })
          );
        }
      }
      if (fun) {
        fun();
      }
    },
    async checkTrueFun(not) {
      // 词义强化答对
      this.intensiveWord.endTime = new Date().getTime();
      if (not) {
        //答对了
        if (this.isReview) {
          await this.setWordPass(not);
        } else {
          //判断第一次正确还是错误
          console.log(this.intensiveWord, "this.intensiveWord111111");
          if (
            this.intensiveWord.firstIsTrue !== true &&
            this.intensiveWord.firstIsTrue !== false
          ) {
            this.intensiveWord.firstIsTrue = !this.intensiveWord.wrongNum > 0;
          }
          if (
            this.intensiveWord.firstIsTrue === true
            // &&this.intensiveWord.num >= 1
          ) {
            console.log("答对发送请求");
            await this.setWordExercise(not);
          } else if (
            this.intensiveWord.firstIsTrue === false
            // &&this.intensiveWord.num >= 2
          ) {
            console.log("答错发送请求");
            await this.setWordExercise(not);
          } else {
            console.log("插入");
            let initUseTime = 0;
            if (this.intensiveWord.endTime && this.intensiveWord.startTime) {
              initUseTime = parseInt(
                (this.intensiveWord.endTime - this.intensiveWord.startTime) /
                  1000
              );
            }
            if (this.intensiveWord.initUseTime) {
              initUseTime += this.intensiveWord.initUseTime;
            }
            let wordData = Object.assign({}, this.intensiveWord, {
              isReview: true,
              wrongNum: 0,
              num: this.intensiveWord.num + 1,
              initUseTime,
            });
            this.insertIntensiveWord(wordData);
          }
        }
      } else {
        // 答错了
        this.intensiveWord.wrongNum++;
      }
    },
    // 词义强化隔两个插入
    insertIntensiveWord(wordData) {
      // 获取词义强化的题目
      let data = {
        book_id: this.checkedBookData.book_id,
        question_type: 6,
        source: this.category,
        unit_id_list: [this.unitId],
        word_id_list: [wordData.word_id],
      };
      create(data).then((res) => {
        console.log(res, "res");
        // if (res.code == 200 && res.data) {
        //   let question = res.data[0];
        //   question.studentAnswer = "";
        //   question.isChecked = false;
        //   question.trueAnswer = "";
        //   question.audioURL = wordData.audioURL;
        //   let answerData = question.answer_list.filter((item) => {
        //     return item.is_true == 1;
        //   });
        //   if (answerData.length > 0) {
        //     question.trueAnswer = answerData[0].paraphrase;
        //   }
        //   wordData.question = question;
        //   if (this.intensiveWordIndex + 3 < this.intensiveWordList.length) {
        //     this.intensiveWordList.splice(
        //       this.intensiveWordIndex + 3,
        //       0,
        //       wordData
        //     );
        //   } else {
        //     this.intensiveWordList.push(wordData);
        //   }
        // }
      });
    },
    goStudyCenter() {
      this.$router.push({
        name: "naturalSpell",
      });
    },
    getStudyWordList() {
      let params = {
        unitId: this.unitId,
        phoneticCategory: this.$store.getters.isBritish,
        bookId: this.checkedBookData.book_id,
        number: this.checkedBookData.number,
        source: this.category,
      };
      EventBus.$emit("openLoading", {});
      getStudyWordList(params)
        .then((res) => {
          if (
            res.code == 200 &&
            res.data &&
            res.data.word_pronunciation_vo_list &&
            res.data.word_pronunciation_vo_list.length > 0
          ) {
            if (
              this.groupData &&
              this.groupData.group_id &&
              this.groupData.group_id !== res.data.group_id
            ) {
              this.addIntegral(this.groupData.group_id);
              this.setInitWordNum();
            }
            // 结算学币
            res.data.word_pronunciation_vo_list.forEach((item) => {
              let paraphrase = [];
              item.word_paraphrase_vo_list.map((item2) => {
                paraphrase.push(
                  (item2.word_sex ? item2.word_sex : "") + item2.paraphrase
                );
              });
              item.id = item.word_id; //ID
              // item.name = item.word_name; //单词
              // item.phonetic = item.phonetic; //音标
              item.imgURL =
                item.word_picture_vo_list.length > 0
                  ? item.word_picture_vo_list[0].url
                  : ""; //图片
              item.exampleList = item.word_example_vo_list; //例句
              item.audioURL = item.word_audio_vo_list[0]
                ? item.word_audio_vo_list[0].url
                : ""; //音频
              item.paraphrase = paraphrase; //释义
            });
            this.checkedWordIndex = -1;
            this.intensiveWordIndex = -1;
            this.groupData = res.data;
            let reviewData = res.data.word_pronunciation_vo_list.filter(
              (word) => {
                return word.is_skip == 1 && word.is_finish == 0;
              }
            );
            reviewData.forEach((item) => {
              item.isReview = true;
            });
            let studyData = res.data.word_pronunciation_vo_list.filter(
              (word) => {
                return word.is_skip == 0;
              }
            );
            let wordListData = [...reviewData, ...studyData];

            if (wordListData.length > 0) {
              EventBus.$emit("closeLoading", {});
              this.isIintensiveWord = false;
              this.wordList = wordListData;
              this.nextWord();
            } else {
              this.intensiveWordList = res.data.word_pronunciation_vo_list.filter(
                (word) => {
                  word.checkedNum = 0;
                  word.wrongNum = 0;
                  return word.is_finish == 1 && word.correct_num < 1;
                }
              );
              // 获取词义强化的题目
              let data = {
                book_id: this.checkedBookData.book_id,
                question_type: 6,
                source: this.category,
                unit_id_list: [this.unitId],
                word_id_list: this.intensiveWordList.map(
                  (item) => item.word_id
                ),
              };
              create(data)
                .then((res) => {
                  console.log(res, "rs");
                  EventBus.$emit("closeLoading", {});
                  if (res.code == 200 && res.data) {
                    this.intensiveWordList.forEach((item) => {
                      let questionData = res.data.filter((question) => {
                        return question.word_id == item.word_id;
                      });
                      if (questionData.length > 0) {
                        let question = questionData[0];
                        question.studentAnswer = "";
                        question.isChecked = false;
                        question.trueAnswer = "";
                        question.phonetic = item.phonetic;
                        question.audioURL = item.audioURL;
                        let answerData = question.answer_list.filter((item) => {
                          return item.is_true == 1;
                        });
                        if (answerData.length > 0) {
                          question.trueAnswer = answerData[0].paraphrase;
                        }
                        item.question = Object.assign({}, question);
                        item.num = 0;
                      }
                    });
                    this.isIintensiveWord = true;
                    this.nextIntensiveWord();
                  }
                })
                .catch(() => {
                  EventBus.$emit("closeLoading", {});
                });
            }
          } else {
            EventBus.$emit("closeLoading", {});
            if (this.groupData && this.groupData.group_id) {
              this.addIntegral(this.groupData.group_id);
            }
            if (!this.isOpenMessageBox) {
              this.isOpenMessageBox = true;
              this.$alert("智能记忆学习已完成,即将前往学习中心", "提示", {
                confirmButtonText: "确定",
                callback: (action) => {
                  this.goStudyCenter()
                  // this.$message({
                  //   type: "info",
                  //   message: `action: ${action}`,
                  // });
                },
              });
              // this.$confirm("智能记忆学习已完成,前往极速挑战", "提示", {
              //   confirmButtonText: "极速模式",
              //   cancelButtonText: "普通模式",
              //   showClose: true,
              //   distinguishCancelAndClose: true,
              //   closeOnClickModal: false,
              //   closeOnPressEscape: false,
              //   beforeClose: (action, instance, done) => {
              //     this.$beforeConfirmClose(action, instance, done);
              //   },
              // })
              //   .then(() => {
              //     this.isOpenMessageBox = false;
              //     this.$router.push({
              //       name: "quickTest",
              //       query: {
              //         unitId: this.unitId,
              //         category: this.category,
              //       },
              //     });
              //   })
              //   .catch((type) => {
              //     this.isOpenMessageBox = false;
              //     if (type != "close") {
              //       this.$router.push({
              //         name: "generalTest",
              //         query: {
              //           unitId: this.unitId,
              //           category: this.category,
              //         },
              //       });
              //     } else {
              //       this.$router.push({
              //         name: "studyCenter",
              //       });
              //     }
              //   });
            }
          }
        })
        .catch(() => {
          EventBus.$emit("closeLoading", {});
        });
    },
    setCountTimer() {
      this.countTimerNum = 5;
      if (this.countTimer) {
        clearInterval(this.countTimer);
      }
      this.countTimer = setInterval(() => {
        this.countTimerNum--;
        if (this.countTimerNum <= 0) {
          clearInterval(this.countTimer);
          this.$refs.studyWord.checkFalseFun();
        }
      }, 1000);
    },
    // 复习模块
    getMemoryReview() {
      let data = {
        page_require: {
          page_num: 1,
          page_size: 10,
        },
        category: this.category,
        book_id: this.checkedBookData.book_id,
      };
      getMemoryReview(data).then(async (res) => {
        if (res.code == 200 && res.data) {
          res.data.word_info_list.forEach((item) => {
            item.id = item.word_id; //ID
            item.name = item.word_name; //单词
            item.imgURL = ""; //图片
            item.exampleList = []; //例句
            item.phonetic =
              this.$store.getters.isBritish == 1
                ? item.phonetic_british
                : item.phonetic_american; //音标
            item.audioURL =
              this.$store.getters.isBritish == 1 ? item.en_url : item.us_url; //音频
            item.paraphrase = item.paraphrase.split("\n"); //释义
          });
          let data = res.data.word_info_list.filter((item) => {
            item.checkedNum = 0;
            item.wrongNum = 0;
            return item.time_interval <= 0;
          });
          if (data.length > 0) {
            this.isIintensiveWord = true;
            this.intensiveWordIndex = -1;
            this.intensiveWordList = data;
            // 获取词义强化的题目
            let postData = {
              book_id: this.checkedBookData.book_id,
              question_type: 6,
              source: this.category,
              unit_id_list: this.unitId ? [this.unitId] : null,
              word_id_list: data.map((item) => item.word_id),
            };
            create(postData).then((res) => {
              if (res.code == 200 && res.data) {
                this.intensiveWordList.forEach((item) => {
                  let questionData = res.data.filter((question) => {
                    return question.word_id == item.word_id;
                  });
                  if (questionData.length > 0) {
                    let question = questionData[0];
                    question.studentAnswer = "";
                    question.isChecked = false;
                    question.trueAnswer = "";
                    question.phonetic = item.phonetic;
                    question.audioURL = item.audioURL;
                    let answerData = question.answer_list.filter((item) => {
                      return item.is_true == 1;
                    });
                    if (answerData.length > 0) {
                      question.trueAnswer = answerData[0].paraphrase;
                    }
                    item.question = Object.assign({}, question);
                  }
                });
                this.isIintensiveWord = true;
                this.nextIntensiveWord();
              }
            });
          } else {
            // 记忆复习完了
            this.cancelForce();
            if (!this.isOpenMessageBox) {
              this.isOpenMessageBox = true;
              let nextData = await this.getReviewNumber();
              if (nextData) {
                this.$confirm(
                  `智能${
                    wordCategory[this.category].title
                  }已复习完成，是否前往智能${
                    wordCategory[nextData.category].title
                  }复习`,
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    closeOnClickModal: false,
                    closeOnPressEscape: false,
                  }
                )
                  .then(() => {
                    this.isOpenMessageBox = false;
                    this.$router.push({
                      name: wordCategory[nextData.category].route,
                      query: {
                        isReview: true,
                      },
                    });
                  })
                  .catch(() => {
                    this.isOpenMessageBox = false;
                    this.goStudyCenter();
                    return false;
                  });
              } else {
                this.$alert("智能记忆已复习完成", "消息提示", {
                  confirmButtonText: "确定",
                  callback: () => {
                    this.isOpenMessageBox = false;
                    this.goStudyCenter();
                  },
                });
                // this.$confirm(`智能记忆已复习完成`, "提示", {
                //   confirmButtonText: "返回学习中心",
                //   cancelButtonText: "取消",
                //   closeOnClickModal: false,
                //   closeOnPressEscape: false,
                // })
                //   .then(() => {
                //     this.isOpenMessageBox = false;
                //     this.goStudyCenter();
                //   })
                //   .catch(() => {
                //     this.isOpenMessageBox = false;
                //     return false;
                //   });
              }
            }
          }
        }
      });
    },
    getReviewNumber() {
      return new Promise((reslove) => {
        getReviewNumber(this.checkedBookData.book_id)
          .then((res) => {
            if (res.code == 200 && res.data) {
              console.log(res);
              let data = res.data.filter((item) => {
                return item.category > this.category && item.num > 0;
              });
              if (data.length > 0) {
                reslove(data[0]);
              }
            }
            reslove(null);
          })
          .catch(() => {
            reslove(null);
          });
      });
    },
    getStudyData() {
      if (this.isReview) {
        this.getMemoryReview();
      } else {
        this.getStudyWordList();
      }
    },
    closeTimer() {
      clearInterval(this.countTimer);
    },
    addIntegral(groupId) {
      let params = {
        groupId,
        source: this.category,
        bookId: this.checkedBookData.book_id,
        unitId: this.unitId,
        type: 1,
      };
      addIntegral(params).then((res) => {
        if (res.code == 200) {
          this.addIntegralNum += res.data;
        }
      });
    },
    watchKeyDown(e) {
      if (this.isOpenMessageBox) {
        return;
      }
      if (this.isIintensiveWord) {
        if (e.keyCode == 13) {
          this.nextIntQuestion();
        }
        if (!this.intensiveWord.question.isChecked) {
          // console.log(e.keyCode,1515);
          if(e.keyCode == 32){
            console.log("开始");
            this.$refs.readWordItem.audioRecordClick();
          }
          // if (e.keyCode == 49 || e.keyCode == 97) {
          //   this.checkAnswer(1);
          // }
          // if (e.keyCode == 50 || e.keyCode == 98) {
          //   this.checkAnswer(2);
          // }
          // if (e.keyCode == 51 || e.keyCode == 99) {
          //   this.checkAnswer(3);
          // }
          // if (e.keyCode == 52 || e.keyCode == 100) {
          //   this.checkAnswer(4);
          // }
        }
      }
      //97-100
    },
    // 1/2/3/4选择选项
    checkAnswer(num) {
      if (
        this.intensiveWord.question.answer_list &&
        this.intensiveWord.question.answer_list[num - 1]
      ) {
        let answer = this.intensiveWord.question.answer_list[num - 1];
        if (this.$refs[`testQuestion`]) {
          this.$refs[`testQuestion`].studentAnswer =
            answer.word_id || answer.word_name || answer.paraphrase;
          this.$refs[`testQuestion`].changeStudentAnswer();
        }
      }
    },
  },
  created() {
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    let data = this.checkedBookData.word_book_vo_list.filter((item) => {
      return item.source == this.category;
    });
    if (data.length > 0) {
      this.checkedBookData.number = data[0].number;
    } else {
      this.checkedBookData.number = 1;
    }
    this.unitId = this.$route.query.unitId;
    this.isReview = !!this.$route.query.isReview;
    this.isForce = Number(this.$route.query.isForce);
    this.getStudyData();
  },
  mounted() {
    window.addEventListener("keydown", this.watchKeyDown);
  },
  beforeDestroy() {
    this.closeTimer();
    window.removeEventListener("keydown", this.watchKeyDown);
  },
};
</script>

<style lang="scss" scoped>
.natural_readWord {
  background: url("~@/assets/img/naturalSpell/read_word.png") no-repeat;
  background-position: center;

  .natural_readWord_center {
    .natural_readWord_content {
      margin: 30px auto 0;
      background: url("~@/assets/img/naturalSpell/read_word_center.png");
      background-size: 1040px 637px;
      width: 1040px;
      height: 637px;

      .title {
        padding-top: 6px;
        position: relative;
        text-align: center;
        font-size: 32px;
        line-height: 66px;
        color: #ffffff;

        .feedback {
          position: absolute;
          right: 46px;
          text-align: center;
          font-size: 20px;
          cursor: pointer;
        }
      }

      .content {
        margin: 19px auto 0;
        width: 954px;
      }
    }
  }
}
</style>
